/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.policy.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.policy.entity.MatMatter;
import org.springblade.modules.policy.entity.PolicyDraw;
import org.springblade.modules.policy.entity.PolicyDrawProcess;
import org.springblade.modules.policy.excel.MatMatterExcel;
import org.springblade.modules.policy.excel.MatMatterImportExcel;
import org.springblade.modules.policy.excel.MatMatterListener;
import org.springblade.modules.policy.service.IMatMatterService;
import org.springblade.modules.policy.service.IPolicyDrawProcessService;
import org.springblade.modules.policy.service.IPolicyDrawService;
import org.springblade.modules.policy.vo.MatMatterVO;
import org.springblade.modules.system.entity.File;
import org.springblade.modules.system.service.IFileService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 控制器
 *
 * @author Blade
 * @since 2022-07-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/blade-policy/matmatter")
@Api(value = "", tags = "接口")
public class MatMatterController extends BladeController {

	private IMatMatterService matMatterService;
	private IPolicyDrawProcessService policyDrawProcessService;
	private IFileService fileService;
	private IPolicyDrawService policyDrawService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入matMatter")
	public R<MatMatter> detail(MatMatter matMatter) {
		MatMatter detail = matMatterService.getOne(Condition.getQueryWrapper(matMatter));
		return R.data(detail);
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入matMatter")
	public R<IPage<MatMatter>> list(@RequestParam(required = false, name = "createTime[]") @DateTimeFormat(pattern = "yyyy-MM-dd") List<Date> createTime, @RequestParam Map<String, Object> matMatter, Query query) {
		matMatter.remove("createTime[]");
		return R.data(matMatterService.selectMatMatterPageByHandelNum(createTime, matMatter, query));
	}

	/**
	 * 统计信息
	 */
	@GetMapping("/handleStatistics")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "统计", notes = "传入matMatter")
	public R<Map<String, Integer>> handleStatistics(@RequestParam(required = false, name = "createTime[]") @DateTimeFormat(pattern = "yyyy-MM-dd") List<Date> createTime, @RequestParam Map<String, Object> matMatter) {
		matMatter.remove("createTime[]");
		return R.data(matMatterService.handleStatistics(createTime, matMatter));
	}

	/**
	 * 分页详情
	 */
	@GetMapping("/getListByHandleNum")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入matMatter")
	public R<List<MatMatter>> getListByHandleNum(@RequestParam String handleNum) {
		QueryWrapper<MatMatter> wrapper = new QueryWrapper<>();
		wrapper.eq(Func.isNotBlank(handleNum), "handle_num", handleNum);
		List<MatMatter> list = matMatterService.list(wrapper);
		return R.data(list);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "分页", notes = "传入matMatter")
	public R<IPage<MatMatterVO>> page(MatMatterVO matMatter, Query query) {
		IPage<MatMatterVO> pages = matMatterService.selectMatMatterPage(Condition.getPage(query), matMatter);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "新增", notes = "传入matMatter")
	public R save(@Valid @RequestBody List<MatMatter> matMatterList) {
		if (CollectionUtils.isNotEmpty(matMatterList)) {
			QueryWrapper<PolicyDrawProcess> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("matter_id", matMatterList.get(0).getHandleNum());
			queryWrapper.orderByAsc("create_time");
			List<PolicyDrawProcess> list = policyDrawProcessService.list(queryWrapper);
			PolicyDraw policyDraw=policyDrawService.getById(matMatterList.get(0).getHandleNum());
			if(ObjectUtil.isEmpty(policyDraw)){
				return R.fail("事项信息错误");
			}
			Date date = new Date();
			Long handleNum = date.getTime();
			matMatterList.forEach((MatMatter matMatter) -> {
				matMatter.setCreateTime(date);
				matMatter.setMatterId(Integer.valueOf(matMatter.getHandleNum()));
				matMatter.setHandleNum("I" + handleNum + matMatter.getHandleNum());
				matMatter.setHandleStatus(list.get(0).getLink());
				matMatter.setDoStateName("办理中");
				matMatter.setHandingDeptId(policyDraw.getCreateUserDept());
				matMatter.setHandingDept(policyDraw.getCreateUserDeptName());
			});
			return R.status(matMatterService.saveBatch(matMatterList));
		}
		return R.fail("企业信息不能为空");
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "修改", notes = "传入matMatter")
	public R update(@Valid @RequestBody MatMatter matMatter) {
		return R.status(matMatterService.updateById(matMatter));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "新增或修改", notes = "传入matMatter")
	public R submit(@Valid @RequestBody MatMatter matMatter) {
		return R.status(matMatterService.saveOrUpdate(matMatter));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(matMatterService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导出办件
	 */
	@SneakyThrows
	@GetMapping("export-mat-matter")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导出办件", notes = "传入matMatter")
	public void exportMatMatter(@RequestParam(required = false, name = "createTime[]") @DateTimeFormat(pattern = "yyyy-MM-dd") List<Date> createTime, @ApiIgnore @RequestParam Map<String, Object> matMatter, HttpServletResponse response) {
		matMatter.remove("createTime[]");
		QueryWrapper<MatMatter> queryWrapper = Condition.getQueryWrapper(matMatter, MatMatter.class);
		queryWrapper.select("handle_num,matter_name, handing_dept, applied_cash_amount,enterprise_code,create_time, finish_time, handle_status");
		if (CollectionUtils.isNotEmpty(createTime)) {
			queryWrapper.between("create_time", createTime.get(0), createTime.get(1));
		}
		queryWrapper.lambda().eq(MatMatter::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<MatMatterExcel> matMatterExcelList = new ArrayList<>();
		List<MatMatter> matMatterList = matMatterService.list(queryWrapper);
		matMatterList.forEach(matMatter1 -> {
			matMatterExcelList.add(Objects.requireNonNull(BeanUtil.copy(matMatter1, MatMatterExcel.class)));
		});
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("办件数据导出", StandardCharsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), MatMatterExcel.class).sheet("办件数据表").doWrite(matMatterExcelList);
	}

	/**
	 * 导出模板
	 */
	@SneakyThrows
	@GetMapping("export-template")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出模板")
	public void exportTemplate(HttpServletResponse response) {
		List<MatMatterImportExcel> list = new ArrayList<>();
		list.add(MatMatterImportExcel.getExcelExample());
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("办件数据模板", StandardCharsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), MatMatterImportExcel.class).sheet("办件数据表").doWrite(list);
	}

	/**
	 * 导入办件
	 */
	@PostMapping("import-mat-matter")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "导入办件", notes = "传入excel")
	public R<List<MatMatterImportExcel>> importMatMatter(MultipartFile file, Integer isCovered) {
		String filename = file.getOriginalFilename();
		if (Func.isEmpty(filename)) {
			throw new RuntimeException("请上传文件!");
		}
		if ((!org.springframework.util.StringUtils.endsWithIgnoreCase(filename, ".xls") && !org.springframework.util.StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
			throw new RuntimeException("请上传正确的excel文件!");
		}
		InputStream inputStream;
		try {
			MatMatterListener listener = new MatMatterListener();
			inputStream = new BufferedInputStream(file.getInputStream());
			ExcelReader excelReader = EasyExcelFactory.read(inputStream, MatMatterImportExcel.class, listener).headRowNumber(1).build();
			excelReader.readAll();
			List<MatMatterImportExcel> list = listener.getDatas();
			excelReader.finish();
			return R.data(list);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.fail("导入失败");
	}
	/**
	 * 审核步骤列表
	 */
	@GetMapping("/getPolicyDrawProcess")
	@ApiOperation(value = "步骤列表", notes = "传入事项id")
	public R<List<PolicyDrawProcess>> getpolicyDrawProcess(MatMatter matMatter){
		QueryWrapper<PolicyDrawProcess> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("matter_id",matMatter.getMatterId());
		queryWrapper.orderByAsc("create_time");
		return R.data(policyDrawProcessService.list(queryWrapper));
	}
	/**
	 * 修改审核状态
	 */
	@PostMapping("/updateHandleStatus")
	@ApiOperation(value = "修改", notes = "传入matMatter")
	public R updateHandleStatus(@Valid @RequestBody MatMatter matMatter) {
		MatMatter matter=matMatterService.getById(matMatter.getId());
		matter.setHandleStatus(matMatter.getHandleStatus());
		matter.setFinishTime(matMatter.getFinishTime());
		matter.setDoStateName(matMatter.getDoStateName());
		return R.status(matMatterService.updateById(matter));
	}
	@GetMapping("/getFileListByMetail")
	@ApiOperation(value = "文件列表",notes = "传入事项id")
	public R<List<File>> getFileListByMetail(MatMatter matMatter){
		List<File> files=new ArrayList<>();
		MatMatter detail=matMatterService.getById(matMatter.getId());
		if(StringUtils.isNotBlank(detail.getMetail())){
			String[] ids=detail.getMetail().split(",");
			QueryWrapper<File> queryWrapper=new QueryWrapper<>();
			queryWrapper.in("id",ids);
			files=fileService.list(queryWrapper);
		}
		return R.data(files);
	}
}
